package xin.yangshuai.activemqgeneral.jms.queueacknowledge;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * JmsConsumer
 *
 * @author shuai
 * @date 2020/6/22
 */
public class JmsConsumer {

    public static final String ACTIVEMQ_URL = "tcp://192.168.124.7:61616";
    public static final String QUEUE_NAME = "queue01-acknowledge";

    public static void main(String[] args) throws JMSException {

        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);

        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();

        //配置为手动签收，需要执行textMessage.acknowledge()
        //如果开启事务，则以事务为准，即使配置为手动签收也不必执行textMessage.acknowledge()，要执行事务的session.commit()。
        Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);

        MessageConsumer messageConsumer = session.createConsumer(session.createQueue(QUEUE_NAME));


        while (true) {
            Message message = messageConsumer.receive(100l);
            if (message != null && message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                System.out.println("****消费者1接收消息-MessageListener++++++TextMessage：" + textMessage.getText());
                //手动签收
                //textMessage.acknowledge();
            } else {
                break;
            }
        }

        messageConsumer.close();

        session.commit();

        session.close();
        connection.close();
    }
}
